################################################################################
# Master Replication Script
# Manuscript: How the Pro-Beijing Media Influences Voters
# Author: Jay C. Kao
# Journal: American Political Science Review
# Date: December 2, 2025
################################################################################

# Clear the workspace to ensure a fresh start
rm(list = ls())

# -----------------------------------------------------------------------------
# 1. Define Required Packages
# -----------------------------------------------------------------------------
# This list contains all libraries needed to replicate tables and figures.
required_packages <- c(
  "tidyverse",  # Data manipulation and visualization
  "estimatr",   # Fast estimators for design-based inference (robust SEs)
  "haven",      # Import/Export SPSS, Stata and SAS Files
  "stargazer",  # Latex table formatting
  "texreg",     # Formatting regression tables
  "interflex",  # Marginal effects and interaction plots
  "cowplot",    # Plot grid arrangements
  "broom",      # Convert statistical objects to tidy tibbles
  "patchwork",  # Combining multiple plots
  "survey",     # Analysis of complex survey samples
  "remotes",    # Helper to install packages from GitHub
  "dotwhisker", # Dot-and-Whisker plots
  "lubridate",  # Date manipulation
  "ggeffects",  # Predicted marginal effects from regression models
  "panelView",  # Panel Data Visualization
  "remotes"     # Install non-CRAN packages
)

# -----------------------------------------------------------------------------
# 2. Install and Load Packages
# -----------------------------------------------------------------------------
# This helper function checks if a package is installed. 
# If not, it installs it. Finally, it loads the package.

install_and_load <- function(packages) {
  
  # Identify missing packages
  missing_packages <- packages[!(packages %in% installed.packages()[, "Package"])]
  
  # Install missing packages if any are found
  if (length(missing_packages) > 0) {
    message("Installing missing packages: ", paste(missing_packages, collapse = ", "))
    install.packages(missing_packages, dependencies = TRUE)
  } else {
    message("All required packages are already installed.")
  }
  
  # Load all packages quietly
  message("Loading packages...")
  invisible(lapply(packages, function(pkg) {
    suppressPackageStartupMessages(library(pkg, character.only = TRUE))
  }))
  
  message("Success: All standard packages installed and loaded.")
}

# Run the setup for CRAN packages
install_and_load(required_packages)



# -----------------------------------------------------------------------------
# 3. Session Info
# -----------------------------------------------------------------------------
# Original Analysis Environment:
# R version 4.5.1 (2025-06-13 ucrt)
# Platform: x86_64-w64-mingw32/x64
# Running under: Windows 11 x64 (build 26200)

# Print current session info for the replicator to compare
sessionInfo()


# Detect the operating system and assign the compatible PDF device
if (Sys.info()["sysname"] == "Darwin") {
  # macOS: Use the native 'pdf' device (works great, no XQuartz needed)
  my_pdf_device <- "pdf" 
} else {
  # Windows/Linux: Use 'cairo_pdf' for better font/transparency support
  my_pdf_device <- cairo_pdf 
}

# -----------------------------------------------------------------------------
# 4. Project Setup & Directory Management
# -----------------------------------------------------------------------------
# IMPORTANT: Ensure your working directory is set to the 'Codes' folder.

# Method 1: Automatic Detection (Best for RStudio users)
if (Sys.getenv("RSTUDIO") == "1") {
  if (!requireNamespace("rstudioapi", quietly = TRUE)) install.packages("rstudioapi")
  
  # getSourceEditorContext() is more reliable for saved files than getActiveDocumentContext()
  script_path <- rstudioapi::getSourceEditorContext()$path
  
  if (script_path == "") {
    warning("Error: Could not detect file path. Please SAVE this file first, or use Method 2.")
  } else {
    setwd(dirname(script_path))
    message("Working directory automatically set to: ", getwd())
  }
}

# Method 2: Manual Fallback
# setwd("path/to/replication/Codes")

# --- Define Output Paths ---
# Scripts are in the Root folder alongside these directories.
tables_dir  <- "Tables"
figures_dir <- "Figures"
data_dir    <- "Data"


# Create output directories if they don't exist.
if (!dir.exists(tables_dir)) {
  dir.create(tables_dir, showWarnings = FALSE)
  message("Created directory: ", tables_dir)
} else {
  message("Directory already exists: ", tables_dir)
}

if (!dir.exists(figures_dir)) {
  dir.create(figures_dir, showWarnings = FALSE)
  message("Created directory: ", figures_dir)
} else {
  message("Directory already exists: ", figures_dir)
}



# -----------------------------------------------------------------------------
# 5. Run Analysis
# -----------------------------------------------------------------------------

# Define your script filenames here
table_script  <- "01_make.tables.R"     # Update this to your exact filename
figure_script <- "02_make.figures.R"    # Update this to your exact filename

# --- Run Table Script ---
if (file.exists(table_script)) {
  message(paste("Running:", table_script))
  message("Outputs will be saved to: ", tables_dir)
  source(table_script, echo = TRUE)
} else {
  warning(paste("SKIPPING: Could not find file '", table_script, "'. Please check the filename or working directory.", sep=""))
}

# --- Run Figure Script ---
if (file.exists(figure_script)) {
  message(paste("Running:", figure_script))
  message("Outputs will be saved to: ", figures_dir)
  source(figure_script, echo = TRUE)
} else {
  warning(paste("SKIPPING: Could not find file '", figure_script, "'. Please check the filename or working directory.", sep=""))
}
